package cn.itcast.n4_共享模型_管程;

import cn.itcast.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import static cn.itcast.util.Sleeper.sleep;

/**
 * <p>
 * Test43_ReentrantLock_利用ReentrantLock锁超时解决哲学家就餐问题
 * </p>
 *
 * @author flyduck
 * @since 2024-10-11
 */
public class Test43_ReentrantLock_利用ReentrantLock锁超时解决哲学家就餐问题 {
    public static void main(String[] args) {
        Chopstick3 c1 = new Chopstick3("1");
        Chopstick3 c2 = new Chopstick3("2");
        Chopstick3 c3 = new Chopstick3("3");
        Chopstick3 c4 = new Chopstick3("4");
        Chopstick3 c5 = new Chopstick3("5");
        // 此时都是先拿左边，后拿右边
        new Philosopher3("苏格拉底", c1, c2).start();
        new Philosopher3("柏拉图", c2, c3).start();
        new Philosopher3("亚里士多德", c3, c4).start();
        new Philosopher3("赫拉克利特", c4, c5).start();
        new Philosopher3("阿基米德", c5, c1).start();
    }
}
/**
 * 哲学家类
 */
@Slf4j(topic = "c.Philosopher3")
class Philosopher3 extends Thread {
    Chopstick3 left;
    Chopstick3 right;

    public Philosopher3(String name, Chopstick3 left, Chopstick3 right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            if (left.tryLock()) {
                try {
                    if (right.tryLock()) {
                        try {
                            eat();
                        }finally {
                            right.unlock();
                        }
                    }
                }finally {
                    left.unlock();
                }
            }
        }
    }

    private void eat() {
        log.debug("eating...");
        Sleeper.sleep(0.5);
    }
}

class Chopstick3 extends ReentrantLock {
    String name;

    public Chopstick3(String name) {
        super(true);
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" + name + '}';
    }
}
